import datetime
import functools
import hashlib
import os
import time
import re


from flask import session, jsonify, request, render_template, current_app, redirect, url_for, g, make_response

from app2 import db
from app2.models.models import News, Follow, User, Category, Collection, Card
from app2.utils.cache.image_cache import upload_image
from app2.utils.common.common import login_user_data2, get_webservertime, vip_get_webservertime, vip_default_time
from app2.utils.pay_url import pay_url_detail
from . import user_blue

url_dict = dict()  # 支付宝接口url


@user_blue.route("/user_info", methods=["GET", "POST"])
@login_user_data2
def user_info():
    # 查询对象
    # user = db.session.query(User).filter(User.id == g.user.id).first()
    user = g.user
    if not user:
        return redirect(url_for("index_blue.index"))
    if vip_get_webservertime() > user.vip_create_time:
        # print('进来了')
        user.vip_create_time = vip_default_time()
        user.vip = 0
        db.session.commit()
    if request.method == "GET":
        # 获取url后的参数，没有则返回 1
        page = request.args.get("page", 1)
        # 获取用户关注的作者，分页显示
        paginate = db.session.query(Collection).filter(Collection.user_id == user.id).paginate(int(page), 3, False)
        print(paginate)
        like_article = paginate.items
        print(len(like_article))
        return render_template("index/user_info.html", user=user, paginate=paginate, like_article=like_article)

    if request.method == "POST":
        # 获取用户信息
        # 如果状态为user_info,则或用户信息
        if "user_info" == request.form.get("user_info"):
            signature = request.form.get("signature")
            nick_name = request.form.get("nick_name")
            gender = request.form.get("gender")
            if not all([signature, nick_name, gender]):
                ret = {
                    "errno": 3003,
                    "errmsg": "缺少参数"
                }
                return jsonify(ret)
            image = request.files.get("avatar")
            if image:
                file_hash = hashlib.md5()
                file_hash.update(image.filename.encode("utf-8"))
                file_name = file_hash.hexdigest() + image.filename[image.filename.rfind("."):]

                file_path = os.path.join(current_app.root_path, "static/upload/images", file_name)
                image.save(file_path)  # 绝对路径
                # 调上传方法
                upload_image(file_path, file_name)

                # 3. 将数据库中对应head_image字段值改为 刚刚保存的图片的路径
                user.avatar_url = "http://ptc817zex.bkt.clouddn.com/" + file_name
                db.session.commit()

            try:
                # 修改数据
                user.signature = signature
                user.nick_name = nick_name
                user.gender = gender
                db.session.commit()
                ret = {
                    "errno": 0,
                    "errmsg": "修改成功！",
                    "avatar_url": user.avatar_url
                }
            except Exception as e:
                ret = {
                    "errno": 3004,
                    "errmsg": "修改失败！"
                }
            return jsonify(ret)

        elif "pwd_info" == request.json.get("user_info"):
            # 获取信息
            old_pwd = request.json.get("old_password")
            new_pwd = request.json.get("new_password")
            if not all([new_pwd, old_pwd]):
                ret = {
                    "errno": 3005,
                    "errmsg": "缺少参数"
                }
                return jsonify(ret)
            # 判断是否是原密码
            user = db.session.query(User).filter(User.password_hash == old_pwd).first()
            if not user:
                ret = {
                    "errno": 3007,
                    "errmsg": "请输入原密码！"
                }
                return jsonify(ret)
            try:
                user.password_hash = new_pwd
                db.session.commit()
                ret = {
                    "errno": 0,
                    "errmsg": "修改成功,请重新登录！"
                }
            except Exception as e:
                ret = {
                    "errno": 3006,
                    "errmsg": "修改成功"
                }
            return jsonify(ret)


@user_blue.route('/sign_in', methods=["POST"])
@login_user_data2
def sign_in():
    """用户签到"""
    user = g.user
    if not user:
        ret = {
            "errno": 3001,
            "errmsg": "请登录！"
        }
        return jsonify(ret)
    if vip_get_webservertime() > user.vip_create_time:
        # print('进来了')
        user.vip_create_time = vip_default_time()
        user.vip = 0
        db.session.commit()
    # 获取当前网络时间
    net_time = get_webservertime()
    print(net_time, "-"*30)
    print(net_time[:4], net_time[5:7], net_time[8:])
    # return "haha"
    if not user.sign_in:
        user.sign_in = net_time
        if user.vip:
            ret = {
                "errno": 0,
                "errmsg": "签到成功, VIP用户 积分 +20"
            }
            user.integral += 20  # VIP每次签到加10分
        else:
            ret = {
                "errno": 0,
                "errmsg": "签到成功, 普通用户 积分 +10"
            }
            user.integral += 10  # 普通每次签到加10分
        db.session.commit()
        return jsonify(ret)
    else:
        # 将当前网络时间转化为datetime.datetime对象， 从凌晨开始
        now_time = datetime.datetime(int(net_time[:4]), int(net_time[5:7]), int(net_time[8:]))  # 2019-02-28 00:00:00
        print(now_time, "now_time")
        # 获取用户数据库的上次签到的时间
        last_sign_in_time = user.sign_in
        # 将用户上次的签到时间改为datetime.datetime对象
        last_time = datetime.datetime(int(last_sign_in_time[:4]), int(last_sign_in_time[5:7]), int(last_sign_in_time[8:]))
        print(last_time, "last_time")
        # 获取两个datetime.datetime对象的timedeltal对象
        timedeltal1 = now_time - last_time  # 两个日期相差的时间
        timedeltal1_str = timedeltal1.__str__()
        print(timedeltal1_str, "两次签到相距的时间")
        # if timedeltal1_str[:+1]:
        #     pass
        # 用正则来获取相差的天数
        try:
            sub_day = re.match(r'[0-9]+', timedeltal1_str).group()
        except Exception as e:
            print("try错误原因", e)
            ret = {
                "errno": 3008,
                "errmsg": "签到失败"
            }
            return jsonify(ret)
        print(sub_day, "-"*30+"两次签到相距的时间", timedeltal1_str)
        # print(type(sub_day))
        # 若相差的天数为1天及以上，则可以签到
        if int(sub_day) >= 1:
            user.sign_in = net_time
            if user.vip:
                user.integral += 20  # VIP每次签到加10分
                ret = {
                    "errno": 0,
                    "errmsg": "签到成功, VIP用户 积分 +20"
                }
            else:
                ret = {
                    "errno": 0,
                    "errmsg": "签到成功, 普通用户 积分 +10"
                }
                user.integral += 10  # 普通每次签到加10分
            db.session.commit()
            return jsonify(ret)
        else:
            ret = {
                "errno": 3003,
                "errmsg": "您今天已签到"
            }
            return jsonify(ret)


@user_blue.route("/pay_info", methods=["GET", "POST"])
@login_user_data2
def pay_info():
    user = g.user
    if not user:
        return redirect(url_for('index_blue.index'))
    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0
    return render_template('index/zfb_pay.html', user=user, ranks_news=ranks_news)


# @user_blue.route("/pay_ment", methods=["GET", "POST"])
# @login_user_data2
# def pay_ment():
#     """实现支付页面"""
#     user = g.user
#     if request.method == "GET":
#         print(request.args)
#         docVlGender = request.args.get("docVlGender")
#         radio1 = request.args.get("radio1")
#
#         # 支付测试简单流程
#         # 检验必备的参数
#         # print(radio1)
#         print(docVlGender)
#         print(user.nick_name)
#
#         # 调用支付接口函数生成支付url
#         p_url = pay_url_detail(user.nick_name, docVlGender)
#         url_dict['url'] = p_url
#         # 关联支付宝API接口(简单演示)需要设计支付页面
#         temp = render_template('index/pay_button.html', user=g.user, pay=p_url, point=docVlGender)
#         response = make_response(temp, 200)
#         # # 修改数据库数据变更积分(需要post向服务器发送数据验证)
#         # g.user.integral += int(docVlGender)
#         # # 开通VIP等级验证--判断积分多少--
#         # g.user.vip = 1  # 充值实现VIP
#         # db.session.commit()
#         return response
#     elif request.method == 'POST':
#         print(request.json)
#         # 验证数据完整性
#         user = request.json.get('user')  # 操作的用户
#         point = request.json.get('point')  # 充值的金额
#         addr = request.json.get('addr')  # 链接地址
#         # 支付宝链接地址
#         # p_url = pay_url_detail(g.user.nick_name, point)
#         # print('支付宝链接地址', type(p_url), p_url)
#         # 判断数据完整性
#         if not(user and point and addr):
#             ret = {
#                 "errno": 1001,
#                 "errmsg": "订单数据缺少"
#             }
#             return jsonify(ret)
#
#         # 支付成功
#         if addr == url_dict['url']:
#             # 修改数据库数据
#             g.user.integral += int(point)
#             # 开通VIP等级验证
#             g.user.vip = 1  # 充值实现VIP
#             if g.user.vip_create_time == vip_default_time():
#                 g.user.vip_create_time = vip_get_webservertime() + datetime.timedelta(days=30)
#             else:
#                 g.user.vip_create_time = g.user.vip_create_time + datetime.timedelta(days=30)
#
#             db.session.commit()
#             ret = {
#                 "errno": 0,
#                 "errmsg": "支付中....."
#             }
#             return jsonify(ret)
#         # 取消支付
#         elif addr == '#':
#             ret = {
#                 "errno": 1002,
#                 "errmsg": "取消订单成功"
#             }
#             return jsonify(ret)
#         # 其他操作失败
#         else:
#             ret = {
#                 "errno": 1003,
#                 "errmsg": "操作失败"
#             }
#             return jsonify(ret)


@user_blue.route("/wx_pay", methods=["GET", "POST"])
@login_user_data2
def wx_pay():
    """微信扫码支付"""
    user = g.user
    if not user:
        return redirect(url_for('index_blue.index'))
    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0
    return render_template('index/wx_pay.html', user=user, ranks_news=ranks_news)


@user_blue.route("/other_pay", methods=["GET", "POST"])
@login_user_data2
def other_pay():
    user = g.user
    if not user:  # 若用户无登录，则重定向
        return redirect(url_for('index_blue.index'))
    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到

    if net_time == user.sign_in:
        user.sing = 1
    else:
        user.sing = 0

    if vip_get_webservertime() > user.vip_create_time:
        # print('进来了')
        user.vip_create_time = vip_default_time()
        user.vip = 0
        db.session.commit()
    return render_template("index/other_pay.html", user=user, ranks_news=ranks_news)


@user_blue.route("/other_pay_judge", methods=["GET", "POST"])
@login_user_data2
def other_pay_judge():
    user = g.user
    if not user:  # 若用户无登录，则重定向
        return redirect(url_for('index_blue.index'))

    if vip_get_webservertime() > user.vip_create_time:
        # print('进来了')
        user.vip_create_time = vip_default_time()
        user.vip = 0
        db.session.commit()

    card_num = request.form.get('card_num')
    card_pass = request.form.get('card_pass')
    if not all([card_num, card_pass]):
        ret = {
            "errno": 3009,
            "errmsg": "请认真填写卡号与密码"
        }
        return jsonify(ret)

    card = db.session.query(Card).filter(Card.num==card_num, Card.password==card_pass).first()
    if not card:
        ret = {
            "errno": 3010,
            "errmsg": "该卡密不存在或已被使用"
        }
        return jsonify(ret)

    # 增加vip
    user.vip = 1
    if user.vip_create_time == vip_default_time():
        user.vip_create_time = vip_get_webservertime() + datetime.timedelta(days=30)
    else:
        user.vip_create_time = user.vip_create_time + datetime.timedelta(days=30)

    # 从数据库删除该卡密
    db.session.delete(card)
    db.session.commit()
    ret = {
        "errno": 3011,
        "errmsg": "充值成功，请到个人中心中查看"
    }
    return jsonify(ret)





